﻿using LDC_Shop_A.Models;
using LDC_Shop_A.Models.Database;
using LDC_Shop_A.Service;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace LDC_Shop_A.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UserController : ControllerBase
    {

        private readonly LDC_ShopAContext _db;
        private readonly IJWTService _jwtservice;

        public UserController(LDC_ShopAContext db, IJWTService jwtservice)
        {
            _db = db;
            _jwtservice = jwtservice;
        }

        //从控制器的构造函数取服务


        /// <summary>
        /// 注册接口（用户使用手机号码，密码进行注册，密码需要二次确认）
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Register(RegisterRequest request)
        {
            //if (string.IsNullOrEmpty(request.Mobile))
            //    return "手机号码不能为空";
            //if(request.Mobile.Length != 11)
            //    return "手机号码格式不正确";

            //1、两次密码是否一致
            if (request.Password != request.CirPassword)
                return "两次密码输入不一致";
            //2、手机号码在数据库是否存在 去数据库查一下有没有这个手机号码
            if (_db.Users.Any(x => x.Mobile == request.Mobile))
                return "手机号码已存在";

            //数字随机字符串
            var salt = new Random().Next(1000, 10000);

            //加入一步  把明文密码  转换成 md5字符串
            var md5 = MD5Helper.MD5Encrypt32(request.Password + salt);

            //3、添加用户到数据库
            var user = new User
            {
                CreateTime = DateTime.Now,
                Mobile = request.Mobile,
                Password = md5,
                Nickname = string.Empty,
                Photo = string.Empty,
                Salt=salt.ToString()
            };
            _db.Users.Add(user);
            //保存更改
            var row = _db.SaveChanges();
            if (row > 0)
                return "注册成功";
            return "注册失败";
        }

        /// <summary>
        /// 登录接口 用户使用手机号码，密码进行登录，登录后可访问需要授权的页面）
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Login(LoginRequest request)
        {
            //1、用账号（手机号码）查询用户
            var user = _db.Users.FirstOrDefault(x => x.Mobile == request.Mobile);
            //2、判断用户是否存在
            if (user == null)
                return "用户不存在";

            //3、判断用户密码是否正确

            //当用户表密码字段使用char(20)   
            //123456
            //输入的密码 "123456"
            //   ！= 成立
            //数据库密码 "123456           "
            //                                   输入密码 明文 + 数据库里盐值
            var md5 = MD5Helper.MD5Encrypt32(request.Password + user.Salt);

            //     md5                      明文密码
            if (user.Password != md5)
                return "密码不正确";
            //4、创建token
            return _jwtservice.CreateToken(user.UserId.ToString(), user.Photo);
        }


        //个人中心（需要查询用户各订单状态数量，用户头像，用户昵称（如果没有设置昵称用手机号码代替））
        /// <summary>
        /// 个人中心
        /// </summary>
        [HttpPost]
        [Authorize]
        public GetUserInfoResponse GetUserInfo()
        {
            //谁的信息 登录用户 Token 
            var userId = Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value;
            //123  ==  "123"
            //主键                                                                 
            var user = _db.Users.FirstOrDefault(x => x.UserId == Convert.ToInt32(userId));
            if (user == null)
                return null;

            //用户头像，用户昵称
            var response = new GetUserInfoResponse
            {
                Photo = user.Photo,
                NickName = user.Nickname,
            };
            if (string.IsNullOrEmpty(response.NickName))
                response.NickName = user.Mobile;
            return response;
        }

        //修改用户信息（需要修改头像，用户昵称）
        
        [HttpPost]
        [Authorize]
        public string UpdateUserInfo(UpdateUserInfoRequest request)
        {
            //谁的信息 登录用户 Token 
            //谁的信息 登录用户 Token 
            var userId = Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value;
            //主键
            var user = _db.Users.FirstOrDefault(x => x.UserId == Convert.ToInt32(userId));
            if (user == null)
                return null;

            user.Nickname = request.NickName;
            user.Photo = request.Photo;
            _db.Users.Update(user);

            //保存更改
            var row=_db.SaveChanges();
            if (row > 0)
                return "修改成功";
            return "修改失败";
        }
    }
}
